package com.libgdxbar.pvzlikegame.entities;

import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Shape2D;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.Array;

import org.libgdxbar.projects.interfaces.ICollision;
import org.libgdxbar.projects.interfaces.callback.CollisionCallback;

public class RectMoveableCollisableEntity extends RectEntity implements ICollision {
	// 组合优于继承 -_- 其实是 Java 没有多继承不得不这么干
	MoveableEntity moveableEntity;
	CollisionCallback collisionCallback = null;
	Array<ICollision> collisionEntities = null;

	public RectMoveableCollisableEntity(float x, float y, Vector2 size) {
		super(x, y, size);
		moveableEntity = new MoveableEntity(x, y, 0, 0);
	}

	public RectMoveableCollisableEntity(Vector2 position, Vector2 size) {
		super(position, size);
		moveableEntity = new MoveableEntity(position);
	}

	public RectMoveableCollisableEntity(float x, float y, float width, float height) {
		super(x, y, width, height);
		moveableEntity = new MoveableEntity(x, y);
	}

	public MoveableEntity getMoveableEntity() {
		return moveableEntity;
	}

	public void setCollisionCallback(CollisionCallback callback) {
		this.collisionCallback = callback;
	}

	public void addCollisionEntity(ICollision entity) {
		if (collisionEntities == null) {
			collisionEntities = new Array<>();
		}
		collisionEntities.add(entity);
	}

	public void setCollisionEntities(Array<ICollision> entities) {
		this.collisionEntities = entities;
	}

	@Override
	public void run(float delta) {
		moveableEntity.run(delta);
		rect.setPosition(moveableEntity.getX(), moveableEntity.getY());
		if (collisionEntities != null) {
			for (ICollision entity : collisionEntities) {
				entity.overlap(getShape());
			}
		}
	}

	@Override
	public Shape2D getShape() {
		return rect;
	}

	@Override
	public boolean overlap(Shape2D shape) {
		// 限制只能和矩形碰撞检测
		// 其他种类碰撞检测如非 Gdx 自带的请自己实现算法
		// 不过应该是用不到的 谁不喜欢矩形呢
		if (this.rect != shape && shape instanceof Rectangle) {
			boolean isContains = this.rect.overlaps((Rectangle) shape);
			// 如果发生碰撞且回调函数存在就调用回调函数
			if (isContains && collisionCallback != null) {
				collisionCallback.onOverlap(shape);
			}
			return isContains;
		}
		// 其他种类都不检测 这不是 bug
		return false;
	}
}
